<?php

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Dcat\Admin\Traits\Resizable;
class FhNews extends Model
{

    protected $table = 'fh_news';
    public static function boot()
    {
        parent::boot();
        static::saving(function ($model) {
           
            $tags = $model->tags;
            $data = FhTag::whereIn('id',explode(',',$tags))->select("c_name","url")->get();

            $content = $model->content;
            foreach($data as $v){
                $htmls = '<a style="color:#7bcd40;" href="'.$v['url'].'" title="'.$v['c_name'].'" target="_blank">'.$v['c_name'].'</a>';
                $content = str_replace($v['c_name'],$htmls,$content);
            }
            $model->content = $content;
    
            $model->description = $model->getHtml($model->content,250)."...";
            
            $subfix = "";
            switch ($model->type) {
                case 1:
                    $subfix = "/industry-info/";
                    break;
                
                case 2:
                    $subfix = "/fongwahnew/";
                    break;
            
                case 3:
                    $subfix = "/information/";
                    break;
            }
            if(strpos($model->url, $subfix) === false){
                $model->url = $subfix.$model->url;
            }

        });
    }

    protected function getUrl($type){
        $subfix = "";
        switch ($type) {
            case 1:
                $subfix = "/industry-info/";
                break;
            
            case 2:
                $subfix = "/fongwahnew/";
                break;
        
            case 3:
                $subfix = "/information/";
                break;
        }
        return $subfix;
    }


    protected function getHtml($html,$maxLength){
        // 使用正则表达式匹配HTML标签
        $pattern = '/<[^>]*>/';
    
        // 去除HTML标签，并获取纯文本内容
        $text = preg_replace($pattern, '', $html);
    
        // 截取指定字符数量的纯文本内容
        $truncatedText = mb_substr($text, 0, $maxLength);
    
        // 如果截取后的文本长度小于原文本长度，表示超出限制，需要找出截取位置
        if(mb_strlen($text) > $maxLength) {

            $truncatedHtml = $truncatedText ;
        } else {
            $truncatedHtml = $html;

        }

        return $truncatedHtml;
    }


   
}
